﻿using Android.App;
using Android.Bluetooth;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Java.Util;
using Java.Util.Logging;
using nhCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WSYmi.MainAct;

namespace WSYmi.BleService
{
    public class BleGattCallback : BluetoothGattCallback
    {
        static string TAG { get; } = typeof(BleGattCallback).FullName;
        private readonly BleService BleService;

        //定义需要进行通信的ServiceUUID
        private readonly UUID ServiceUUID = UUID.FromString("0000ffe0-0000-1000-8000-00805f9b34fb");
        //定义需要进行通信的CharacteristicUUID
        private readonly UUID CharacteristicUUID = UUID.FromString("0000ffe1-0000-1000-8000-00805f9b34fb");
        //private Handler Handler { get; set; } = new Handler(Looper.MyLooper());

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="iBleIO">回调接口</param>
        /// <param name="handler">主窗口消息句柄</param>
        public BleGattCallback(BleService service)
        {
            BleService = service;
        }

        /// <summary>
        /// 连接状态改变
        /// </summary>
        /// <param name="gatt"></param>
        /// <param name="status"></param>
        /// <param name="newState"></param>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public override void OnConnectionStateChange(BluetoothGatt gatt, GattStatus status, ProfileState newState)
        {
            switch (newState)
            {
                case ProfileState.Connected:
                    Log.Debug(TAG, $"蓝牙已经连接：{newState}");
                    gatt.DiscoverServices();//必须有，可以让onServicesDiscovered显示所有Services
                    BleService.BroadcastUpdate(BleService.KEY_State, (int)EnumMessageHandler.BleConnected);
                    BleService.IsBleConn = true;
                    break;
                case ProfileState.Disconnected:
                    Log.Debug(TAG, $"蓝牙连接断开：{newState}");
                    gatt.Close();
                    BleService.BroadcastUpdate(BleService.KEY_State, (int)EnumMessageHandler.BleDisconnected);
                    BleService.IsBleConn = false;
                    BleService.Cmds.Clear();//清空命令，不再发送
                    BleService.IsRunning = false;
                    break;
                default:
                    Log.Debug(TAG, $"未知蓝牙连接状态变化：{newState}");
                    break;
            }
        }

        /// <summary>
        /// 生成命令帧
        /// </summary>
        internal void GetCmdFrame()
        {
            BaseDevice envDevice = new CjkjDevice();

            envDevice.Configs.Add(new ElementConfig("气温", "℃", 2, 4));
            envDevice.Configs.Add(new ElementConfig("气湿", "%", 2, 5));
            envDevice.Configs.Add(new ElementConfig("气压", "hPa", 1, 6));
            ElementConfig config = new ElementConfig("电池", "%", 0, 3);//计算字段
            envDevice.Configs.Add(config);
            envDevice.AdddDecoder(new nhCore.Modbus.PowerDecoder(config));

            foreach (var c in envDevice.GetSentCmds(4, 3000, 3000))
            {
                Cmd cmd = new Cmd(c);
                BleService.Cmds.Add(cmd);
            }
        }

        /// <summary>
        /// 发现服务
        /// </summary>
        /// <param name="gatt"></param>
        /// <param name="status"></param>
        public override void OnServicesDiscovered(BluetoothGatt gatt, GattStatus status)
        {//发现服务，在蓝牙连接的时候会调用
            if (status == GattStatus.Success)
            {
                BluetoothGattCharacteristic gattCharacteristic = null;
                BluetoothGattService gattService = gatt.GetService(ServiceUUID);
                if (gattService != null)
                {
                    Log.Debug(TAG, $"发现指定Servic:{ServiceUUID}");
                    gattCharacteristic = gattService.GetCharacteristic(CharacteristicUUID);
                    if (gattCharacteristic != null)
                    {
                        GetCmdFrame();
                        BleService.Connected(gatt, gattService, gattCharacteristic);
                        Log.Debug(TAG, $"发现指定Charactieristic:{CharacteristicUUID}");
                    }
                }

                if (gattCharacteristic == null)
                {
                    //SendHandlerMessage("不是兼容蓝牙设备。", EnumMessageHandler.NotBleDevice);
                    BleService.BroadcastUpdate("不是兼容蓝牙设备。");
                    gatt.Disconnect();
                }
            }
            else
            {
                Log.Debug(TAG, $"状态失败。GattStatus:{status}");
            }
        }

        /// <summary>
        /// 发送数据后回调
        /// </summary>
        /// <param name="gatt"></param>
        /// <param name="characteristic"></param>
        /// <param name="status"></param>
        public override void OnCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
            GattStatus status)
        {
            if (status == GattStatus.Success)
            {//写入成功
                Log.Debug(TAG, "onCharacteristicWrite中写入成功");
            }
            else if (status == GattStatus.Failure)
            {
                Log.Debug(TAG, "onCharacteristicWrite中写入失败");
            }
            else if (status == GattStatus.WriteNotPermitted)
            {
                Log.Debug(TAG, "onCharacteristicWrite中没权限");
            }
        }

        /// <summary>
        /// 收到设备数据
        /// </summary>
        /// <param name="gatt"></param>
        /// <param name="characteristic"></param>
        public override void OnCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic)
        {
            BleService.OnCharacteristicChanged(gatt, characteristic);
        }

        public override void OnCharacteristicRead(BluetoothGatt gatt,
            BluetoothGattCharacteristic characteristic, GattStatus status)
        {
            //if (status == GattStatus.Success)
            //{
            //    byte[] bytes = characteristic.GetValue();
            //}
        }

        public override void OnDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, GattStatus status)
        {

        }
    }
}